<template>
  <div class="collection-view">
    <n-tree
      block-line
      multiple
      :data="treeData"
      :default-expanded-keys="defaultExpandedKeys"
      :selected-keys="selectedKeys"
      @update:selected-keys="handleSelect"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { NTree } from 'naive-ui'
import { EventsOn } from '../../wailsjs/runtime/runtime'
import { subEvent, pubEvent } from '../api/event'
import { AddFilterDomain, CleanFilterDomains } from '../../wailsjs/go/proxy/Proxy'

const selectedKeys = ref([])
const domainStats = ref(new Map()) // 用于存储域名统计

const treeData = ref([
  {
    label: '收藏夹',
    key: 'favorites',
    children: []
  },
  {
    label: '应用',
    key: 'applications',
    children: []
  },
  {
    label: '域名',
    key: 'domains',
    children: []
  }
])

const defaultExpandedKeys = ref(['favorites', 'applications', 'domains'])

const handleSelect = async (keys) => {
  selectedKeys.value = keys
  
  // 清除所有过滤器
  await CleanFilterDomains()
  
  // 过滤出选中的域名（排除非域名节点）
  const selectedDomains = keys.filter(key => domainStats.value.has(key))
  
  // 为每个选中的域名添加过滤器
  for (const domain of selectedDomains) {
    await AddFilterDomain(domain)
  }
}

// 修改 clearDomainStats 函数
const clearDomainStats = async () => {
  // 保存当前选中的域名
  const selectedDomains = selectedKeys.value.filter(key => domainStats.value.has(key))
  
  domainStats.value.clear()
  
  // 为选中的域名重新设置计数为0
  selectedDomains.forEach(domain => {
    domainStats.value.set(domain, 0)
  })
  
  const domainsNode = treeData.value.find(node => node.key === 'domains')
  if (domainsNode) {
    domainsNode.children = Array.from(domainStats.value).map(([domain, count]) => ({
      label: `${domain} (${count})`,
      key: domain,
      class: selectedKeys.value.includes(domain) ? 'selected-domain' : ''
    }))
  }

  // 重新设置过滤器
  await CleanFilterDomains()
  for (const domain of selectedDomains) {
    await AddFilterDomain(domain)
  }
}

// 处理新的代理请求，统计域名
function handleNewRequest(payload) {
  const data = JSON.parse(payload)
  const host = data.Host
  
  if (host) {
    // 更新域名统计
    const count = (domainStats.value.get(host) || 0) + 1
    domainStats.value.set(host, count)
    
    // 更新树形数据
    const domainsNode = treeData.value.find(node => node.key === 'domains')
    if (domainsNode) {
      domainsNode.children = Array.from(domainStats.value).map(([domain, count]) => ({
        label: `${domain} (${count})`,
        key: domain,
        // 添加样式类以支持高亮
        class: selectedKeys.value.includes(domain) ? 'selected-domain' : ''
      }))
    }
  }
}

// 监听事件
onMounted(() => {
  EventsOn("new_proxy_request", handleNewRequest)
  subEvent("clear-table-data", clearDomainStats)
})
</script>

<style scoped>
.collection-view {
  height: 100%;
  padding: 16px;
}

:deep(.selected-domain) {
  background-color: rgba(24, 160, 88, 0.1);
  font-weight: bold;
}
</style> 